package com.laxcen.glcamera2;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.SeekBar;

import com.laxcen.glcamera2.camera.CameraHelper;
import com.laxcen.glcamera2.camera.CameraListener;
import com.laxcen.glcamera2.view.RoundFrameLayout;
import com.laxcen.glcamera2.view.RoundTextureView;

public class MainActivity extends AppCompatActivity {

    private static final String[] CAMERA_PERMISSION = new String[]{
            Manifest.permission.CAMERA
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
        if (checkPermissions(CAMERA_PERMISSION)) {
            initView();
        }
    }


    private CameraHelper cameraHelper;
    private RoundTextureView textureView;
    private RoundFrameLayout insertFrameLayout;
    private ViewTreeObserver.OnGlobalLayoutListener globalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener(){
        @Override
        public void onGlobalLayout() {
            textureView.getViewTreeObserver().removeOnGlobalLayoutListener(globalLayoutListener);
            ViewGroup.LayoutParams layoutParams = textureView.getLayoutParams();
            int sideLength = Math.min(textureView.getWidth(), textureView.getHeight()) * 3 / 4;
            layoutParams.width = sideLength;
            layoutParams.height = sideLength;
            textureView.setLayoutParams(layoutParams);
            textureView.turnRound();
            initCamera();
        }
    };
    private void initView() {
        textureView = findViewById(R.id.texture_preview);
        textureView.getViewTreeObserver().addOnGlobalLayoutListener(globalLayoutListener);
    }

    private int CAMERA_ID = 1;
    private Camera.Size previewSize;
    private void initCamera(){
        cameraHelper = new CameraHelper.Builder()
                .cameraListener(new CameraListener() {
                    @Override
                    public void onCameraOpened(Camera camera, int cameraId,
                                               int displayOrientation, boolean isMirror) {
                        previewSize = camera.getParameters().getPreviewSize();
                        //在相机打开时，添加右上角的view用于显示原始数据和预览数据
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //将预览控件和预览尺寸比例保持一致，避免拉伸
                                {
                                    FrameLayout.LayoutParams textureViewLayoutParams = (FrameLayout.LayoutParams) textureView.getLayoutParams();
                                    int newHeight = 0;
                                    int newWidth = textureViewLayoutParams.width;
                                    //横屏
                                    if (displayOrientation % 180 == 0) {
                                        newHeight = textureViewLayoutParams.width * previewSize.height / previewSize.width;
                                    }
                                    //竖屏
                                    else {
                                        newHeight = textureViewLayoutParams.width * previewSize.width / previewSize.height;
                                    }
                                    //当不是正方形预览的情况下，添加一层ViewGroup限制View的显示区域
                                    if (newHeight != textureViewLayoutParams.height) {
                                        insertFrameLayout = new RoundFrameLayout(MainActivity.this);
                                        int sideLength = Math.min(newWidth, newHeight);
                                        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(sideLength, sideLength);
                                        insertFrameLayout.setLayoutParams(layoutParams);
                                        FrameLayout parentView = (FrameLayout) textureView.getParent();
                                        parentView.removeView(textureView);
                                        parentView.addView(insertFrameLayout);

                                        insertFrameLayout.addView(textureView);
                                        FrameLayout.LayoutParams newTextureViewLayoutParams = new FrameLayout.LayoutParams(newWidth, newHeight);
                                        //横屏
                                        if (displayOrientation % 180 == 0) {
                                            newTextureViewLayoutParams.leftMargin = ((newHeight - newWidth) / 2);
                                        }
                                        //竖屏
                                        else {
                                            newTextureViewLayoutParams.topMargin = -(newHeight - newWidth) / 2;
                                        }
                                        textureView.setLayoutParams(newTextureViewLayoutParams);
                                    }
                                }
                                insertFrameLayout.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        insertFrameLayout.setRadius(100 * Math.min(insertFrameLayout.getWidth(), insertFrameLayout.getHeight()) / 2 / 100);
                                        insertFrameLayout.turnRound();
                                    }
                                });
                            }
                        });
                    }

                    @Override
                    public void onPreview(byte[] data, Camera camera) {

                    }

                    @Override
                    public void onCameraClosed() {

                    }

                    @Override
                    public void onCameraError(Exception e) {

                    }

                    @Override
                    public void onCameraConfigurationChanged(int cameraID, int displayOrientation) {

                    }
                })
                .specificCameraId(CAMERA_ID)
                .previewOn(textureView)
                .previewSize(new Point(1280, 960))
                // .previewViewSize(new Point(textureView.getLayoutParams().width, textureView.getLayoutParams().height))
                .rotation(getWindowManager().getDefaultDisplay().getRotation())
                .build();
        cameraHelper.start();
    }





    @Override
    protected void onPause() {
        if (cameraHelper != null) {
            cameraHelper.stop();
        }
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (cameraHelper != null) {
            cameraHelper.start();
        }
    }

    /**
     * 权限检查
     *
     * @param neededPermissions 需要的权限
     * @return 是否全被同意
     */
    protected boolean checkPermissions(String[] neededPermissions) {
        if (neededPermissions == null || neededPermissions.length == 0) {
            return true;
        }
        boolean allGranted = true;
        for (String neededPermission : neededPermissions) {
            allGranted &= ContextCompat.checkSelfPermission(this, neededPermission) == PackageManager.PERMISSION_GRANTED;
        }
        return allGranted;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean isAllGranted = true;
        for (int grantResult : grantResults) {
            isAllGranted &= (grantResult == PackageManager.PERMISSION_GRANTED);
        }
        onRequestPermissionResult(requestCode, isAllGranted);
    }

    /**
     * 封装{@link #onRequestPermissionsResult(int, String[], int[])}，回传请求码和是否全部被同意
     *
     * @param requestCode  请求权限时的请求码
     * @param isAllGranted 是否全被同意
     */
    protected void onRequestPermissionResult(int requestCode, boolean isAllGranted) {

    }
}